package com.zmc.lostfound.search.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.zmc.lostfound.common.dto.post.PostDetailInfoDTO;
import com.zmc.lostfound.common.exception.MyException;
import com.zmc.lostfound.common.feign.PostFeign;
import com.zmc.lostfound.common.utils.RegexUtil;
import com.zmc.lostfound.common.utils.Result;
import com.zmc.lostfound.search.service.PostSearchService;
import com.zmc.lostfound.search.vo.PostSearchVO;
import com.zmc.lostfound.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.zmc.lostfound.common.constant.ElasticSearchConstant.ASC;
import static com.zmc.lostfound.common.constant.ElasticSearchConstant.POST_DETAIL_INFO_INDEX;
import static com.zmc.lostfound.common.constant.RegexConstant.NUM_REGEX;

/**
 * @author ZMC
 * @description 帖子信息搜索业务实现类
 * @email 2869581855@qq.com
 * @date 2023-07-05 15:17:37
 */
@Slf4j
@Service
public class PostSearchServiceImpl implements PostSearchService {

    private final PostFeign postFeign;

    private final RestHighLevelClient esRestClient;

    public PostSearchServiceImpl(PostFeign postFeign, RestHighLevelClient esRestClient) {
        this.postFeign = postFeign;
        this.esRestClient = esRestClient;
    }

    /**
     * 多条件搜索帖子详情信息
     *
     * @param postSearchVO 帖子搜索参数请求体
     * @return SearchResult
     */
    @Override
    public SearchResult searchDetailInfo(PostSearchVO postSearchVO) {
        // 1.创建SearchRequest
        SearchRequest request = new SearchRequest(POST_DETAIL_INFO_INDEX);
        SearchSourceBuilder sourceBuilder = request.source();
        // 2.封装DSL查询语句
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String keyword = postSearchVO.getKeyword();
        // 2.1 should查询
        if (StrUtil.isNotBlank(keyword)) {
            // 2.1.1对all进行全文检索
            boolQuery.should(QueryBuilders.matchQuery("all", keyword));
            // 2.1.2对帖子id进行精确查询
            if (!RegexUtil.mismatch(keyword, NUM_REGEX)) {
                boolQuery.should(QueryBuilders.termsQuery("id", keyword));
            }
            // 2.1.3设置帖子标题、地址、发贴人昵称高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder().requireFieldMatch(false);
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            highlightBuilder.field("title");
            highlightBuilder.field("address");
            highlightBuilder.field("fromUser.nickname");
            sourceBuilder.highlighter(highlightBuilder);
            // 2.1.4以上should(或)子查询条件至少匹配一个
            boolQuery.minimumShouldMatch(1);
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 2.2 条件过滤
        // 2.2.1 精确查询---帖子类型(0:寻物，1:认领)
        Integer type = postSearchVO.getType();
        if (type != null) {
            boolQuery.filter(QueryBuilders.termQuery("type", type));
        }
        // 2.2.2 精确查询---物品类型id
        Long itemTypeId = postSearchVO.getItemTypeId();
        if (itemTypeId != null) {
            boolQuery.filter(QueryBuilders.termQuery("itemTypeId", itemTypeId));
        }
        // 2.2.3 精确查询---帖子完成状态(0:未完成，1:已完成)
        Integer completeStatus = postSearchVO.getCompleteStatus();
        if (completeStatus != null) {
            boolQuery.filter(QueryBuilders.termQuery("completeStatus", completeStatus));
        }
        // 2.2.4 精确查询---帖子审核状态(0:未审核，1:未通过，2:已通过)
        Integer reviewStatus = postSearchVO.getReviewStatus();
        if (reviewStatus != null) {
            boolQuery.filter(QueryBuilders.termQuery("reviewStatus", reviewStatus));
        }
        // 2.2.5 精确查询---发贴人id
        Long fromUserId = postSearchVO.getFromUserId();
        if (fromUserId != null) {
            boolQuery.filter(QueryBuilders.termQuery("fromUser.id", fromUserId));
        }
        // 2.2.6 精确查询---完成用户id(寻物/认领人)
        Long toUserId = postSearchVO.getToUserId();
        if (toUserId != null) {
            boolQuery.filter(QueryBuilders.termQuery("toUserId", toUserId));
        }
        // 2.2.7 批量精确查询---帖子ids
        List<Long> postIds = postSearchVO.getPostIds();
        if (CollectionUtil.isNotEmpty(postIds)) {
            boolQuery.filter(QueryBuilders.termsQuery("id", postIds));
        }
        // 2.3添加封装好的DSL查询语句
        sourceBuilder.query(boolQuery);
        // 2.4排序
        // 2.4.1按审核状态升序排序、帖子发布时间降序排序
        sourceBuilder.sort("reviewStatus", SortOrder.ASC);
        sourceBuilder.sort("gmtCreate", SortOrder.DESC);
        // 2.4.2按帖子id排序
        String sortByPostId = postSearchVO.getSortByPostId();
        if (sortByPostId != null) {
            SortOrder sortOrder = ASC.equals(sortByPostId) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort("id", sortOrder);
        }
        // 2.4.3按帖子发布时间排序
        String sortByGmtCreate = postSearchVO.getSortByGmtCreate();
        if (sortByGmtCreate != null) {
            SortOrder sortOrder = ASC.equals(sortByGmtCreate) ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort("gmtCreate", sortOrder);
        }
        // 2.5分页
        Integer pageNo = postSearchVO.getPageNo();
        Integer pageSize = postSearchVO.getPageSize();
        sourceBuilder.from((pageNo - 1) * pageSize);
        sourceBuilder.size(pageSize);
        // 3.发送查询请求，解析响应结果到PageResult并返回
        System.err.println("DSL查询语句 = " + sourceBuilder.toString());
        SearchResult searchResult = new SearchResult();
        searchResult.setPageNo(pageNo);
        searchResult.setPageSize(pageSize);
        searchResult.setTotalCount(0);
        searchResult.setTotalPage(0);
        try {
            // 3.1向ES发送查询请求
            SearchResponse response = esRestClient.search(request, RequestOptions.DEFAULT);
            // 3.2解析ES响应结果
            this.handleResponse(response, searchResult);
        } catch (Exception e) {
            log.error("ES检索帖子详情信息失败: " + e.getMessage(), e);
            MyException.throwException("ES检索帖子详情信息失败: " + e.getMessage());
        }
        return searchResult;
    }

    /**
     * 解析查询结果并封装到SearchResult
     *
     * @param response     ES查询结果
     * @param searchResult 商品检索结果
     */
    private void handleResponse(SearchResponse response, SearchResult searchResult) {
        if (response == null || searchResult == null) {
            return;
        }
        SearchHits searchHits = response.getHits();
        // 1.获取查询总记录数
        long totalCount = searchHits.getTotalHits().value;
        if (totalCount <= 0) {
            return;
        }
        // 1.1设置总记录数
        searchResult.setTotalCount((int) (totalCount));
        // 1.2计算总页数
        searchResult.calculateTotalPage();
        // 2.获取查询的帖子信息
        SearchHit[] hits = searchHits.getHits();
        List<PostDetailInfoDTO> postDetailInfoDTOList = null;
        if (hits != null && hits.length > 0) {
            postDetailInfoDTOList = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                // 2.1反序列化
                PostDetailInfoDTO postDetailInfoDTO = JSONUtil.toBean(json, PostDetailInfoDTO.class);
                // 2.2获取高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (CollectionUtil.isNotEmpty(highlightFields)) {
                    // 根据字段名称获取高亮结果
                    HighlightField titleField = highlightFields.get("title");
                    if (titleField != null) {
                        // 设置高亮数据
                        String title = titleField.getFragments()[0].string();
                        postDetailInfoDTO.setTitle(title);
                    }
                    HighlightField addressField = highlightFields.get("address");
                    if (addressField != null) {
                        String address = addressField.getFragments()[0].string();
                        postDetailInfoDTO.setAddress(address);
                    }
                    HighlightField nicknameField = highlightFields.get("fromUser.nickname");
                    if (nicknameField != null) {
                        String nickname = nicknameField.getFragments()[0].string();
                        postDetailInfoDTO.getFromUser().setNickname(nickname);
                    }
                }
                postDetailInfoDTOList.add(postDetailInfoDTO);
            }
        }
        searchResult.setDataList(postDetailInfoDTOList);
    }

    /**
     * 根据id新增/修改ES的post_detail_info索引库的文档
     *
     * @param id 文档id
     */
    @Override
    public void saveById(Long id) {
        try {
            // 根据id查询从数据库查询UserBaseInfo
            Result result = postFeign.queryDetailInfoByPostId(id);
            if (result != null && HttpStatus.HTTP_OK == result.getCode()) {
                PostDetailInfoDTO postDetailInfoVO = result.getBean("postDetailInfoVO", PostDetailInfoDTO.class);
                // 创建IndexRequest对象
                IndexRequest request = new IndexRequest(POST_DETAIL_INFO_INDEX).id(postDetailInfoVO.getId().toString());
                // 序列化
                request.source(JSONUtil.toJsonStr(postDetailInfoVO), XContentType.JSON);
                // 发送请求
                esRestClient.index(request, RequestOptions.DEFAULT);
            } else if (result != null) {
                log.error("新增/修改post_detail_info索引库的文档" + id + "失败: " + result.getMessage());
                MyException.throwException("新增/修改post_detail_info索引库的文档" + id + "失败: " + result.getMessage());
            } else {
                log.error("新增/修改post_detail_info索引库的文档" + id + "失败");
                MyException.throwException("新增/修改post_detail_info索引库的文档" + id + "失败");
            }
        } catch (Exception e) {
            log.error("新增/修改post_detail_info索引库的文档" + id + "失败: " + e.getMessage(), e);
            MyException.throwException("新增/修改post_detail_info索引库的文档" + id + "失败: " + e.getMessage());
        }
    }

    /**
     * 根据id删除ES的post_detail_info索引库的文档
     *
     * @param id 文档id
     */
    @Override
    public void deleteById(Long id) {
        try {
            // 1.创建DeleteRequest对象
            DeleteRequest request = new DeleteRequest(POST_DETAIL_INFO_INDEX, String.valueOf(id));
            // 2.发送请求
            esRestClient.delete(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("删除post_detail_info索引库的文档" + id + "失败: " + e.getMessage(), e);
            MyException.throwException("删除post_detail_info索引库的文档" + id + "失败: " + e.getMessage());
        }
    }

}
